<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品详情 - 校园二手交易平台</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .item-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 15px;
        }
        .item-price {
            font-size: 20px;
            color: #e74c3c;
            margin-bottom: 15px;
        }
        .item-description {
            margin-bottom: 15px;
        }
        .btn {
            padding: 10px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        .btn:hover {
            background: #5a6fd8;
        }
        .btn-outline {
            padding: 10px 20px;
            background: transparent;
            color: #667eea;
            border: 1px solid #667eea;
            border-radius: 5px;
            cursor: pointer;
        }
        /* Comments Section Styles */
        .comment-item {
            background-color: #f9f9f9;
            border: 1px solid #eee;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .comment-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            font-size: 14px;
            color: #555;
        }
        .comment-author {
            font-weight: bold;
            color: #333;
        }
        .comment-date {
            color: #888;
        }
        .comment-content {
            line-height: 1.6;
            color: #333;
            white-space: pre-wrap; /* Preserve whitespace and line breaks */
        }
        .delete-comment-btn {
            background-color: #dc3545;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            margin-left: 10px;
            transition: background-color 0.3s;
        }
        .delete-comment-btn:hover {
            background-color: #c82333;
        }

        /* New style for unread comments notification on item detail page */
        .item-comment-notification {
            display: none; /* Hidden by default */
            background-color: #ffc107; /* Warning color */
            color: #343a40; /* Dark text for contrast */
            border-radius: 5px;
            padding: 3px 8px;
            font-size: 13px;
            font-weight: bold;
            margin-left: 10px;
            vertical-align: middle;
        }
    </style>
</head>
<body>
<div class="container">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
        <div class="item-title" id="itemTitle" style="margin-bottom: 0;"></div>
        <button class="btn-outline" onclick="history.back()">返回</button>
    </div>
    <div class="item-price" id="itemPrice"></div>
    <div class="item-description" id="itemDescription"></div>
    <div style="margin-bottom: 15px;">
        发布者: <a href="#" id="sellerNicknameLink" style="text-decoration: none; color: #667eea;"></a>
    </div>
    <div class="item-image-container">
        <img id="itemImage" src="" alt="商品图片" style="max-width: 100%; height: auto;"/>
        <div id="noImage" style="display: none; text-align: center; color: #888;">暂无图片</div>
    </div>

    <div style="margin-top: 20px; display: flex; justify-content: flex-end; gap: 10px;">
        <button class="btn" id="favoriteBtn">收藏</button>
        <button class="btn" id="editItemBtn" style="display: none;">编辑商品</button>
        <span id="itemUnreadCommentsBadge" class="item-comment-notification">新评论</span>
    </div>

    <!-- Comments Section -->
    <div class="container" style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;">
        <h3 style="margin-top: 0; margin-bottom: 20px;">商品评论</h3>
        <div id="commentsList" style="margin-bottom: 20px;"></div>

        <div class="comment-form">
            <h4>发表评论</h4>
            <textarea id="commentContent" placeholder="请输入您的评论..." style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; min-height: 80px; margin-bottom: 10px;"></textarea>
            <button class="btn" id="submitCommentBtn">提交评论</button>
        </div>
    </div>
</div>

<!-- Edit Item Modal -->
<div id="editItemModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); justify-content: center; align-items: center; z-index: 101;">
    <div style="background: white; padding: 20px; border-radius: 8px; max-width: 500px; width: 90%; box-shadow: 0 4px 15px rgba(0,0,0,0.2);">
        <h3 style="margin-top: 0; margin-bottom: 20px; text-align: center;">编辑商品信息</h3>
        <form id="editItemForm">
            <input type="hidden" id="editItemId">
            <div style="margin-bottom: 15px;">
                <label for="editTitle" style="display: block; margin-bottom: 5px; font-weight: bold;">标题:</label>
                <input type="text" id="editTitle" required style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
            </div>
            <div style="margin-bottom: 15px;">
                <label for="editPrice" style="display: block; margin-bottom: 5px; font-weight: bold;">价格:</label>
                <input type="number" id="editPrice" step="0.01" required style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
            </div>
            <div style="margin-bottom: 15px;">
                <label for="editDescription" style="display: block; margin-bottom: 5px; font-weight: bold;">描述:</label>
                <textarea id="editDescription" required style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; height: 100px;"></textarea>
            </div>

            <div style="margin-bottom: 15px;">
                <label for="editStatus" style="display: block; margin-bottom: 5px; font-weight: bold;">状态:</label>
                <select id="editStatus" style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
                    <option value="出售中">出售中</option>
                    <option value="已售出">已售出</option>
                    <option value="已下架">已下架</option>
                </select>
            </div>
            <div style="margin-bottom: 15px;">
                <label for="editImages" style="display: block; margin-bottom: 5px; font-weight: bold;">图片 (选择新图片将替换原有图片):</label>
                <input type="file" id="editImages" accept="image/*" multiple style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
            </div>

            <div style="display: flex; justify-content: flex-end; gap: 10px;">
                <button type="button" class="btn-outline" onclick="closeEditModal()">取消</button>
                <button type="submit" class="btn">保存</button>
            </div>
        </form>
    </div>
</div>

<script>
    // Add logic to get current user
    let currentUser = null;

    function getCurrentUser() {
        const userData = localStorage.getItem('user');
        if (userData) {
            currentUser = JSON.parse(userData);
        }
        return currentUser;
    }

    let currentItemData = null; // Store current item data globally for comment submission

    async function loadItemDetail() {
        const urlParams = new URLSearchParams(window.location.search);
        const itemId = urlParams.get('id');
        const currentUser = getCurrentUser(); // Get current user
        const favoriteBtn = document.getElementById('favoriteBtn');

        try {
            const response = await fetch(`/api/items/${itemId}`);
            const item = await response.json();
            currentItemData = item; // Store item data
            console.log("Item data loaded:", currentItemData); // Added log

            document.getElementById('itemTitle').textContent = item.title;
            document.getElementById('itemPrice').textContent = `价格: ¥${item.price}`;
            document.getElementById('itemDescription').textContent = item.description;

            // Display seller nickname
            const sellerNicknameLink = document.getElementById('sellerNicknameLink');
            if (item.sellerNickname) {
                sellerNicknameLink.textContent = item.sellerNickname;
                sellerNicknameLink.removeAttribute('href'); 
            } else {
                sellerNicknameLink.textContent = '未知用户';
                sellerNicknameLink.removeAttribute('href'); 
            }

            // Display image
            const itemImage = document.getElementById('itemImage');
            const noImageDiv = document.getElementById('noImage');
            if (item.base64Image) {
                itemImage.src = item.base64Image;
                itemImage.style.display = 'block';
                noImageDiv.style.display = 'none';
            } else {
                itemImage.style.display = 'none';
                noImageDiv.style.display = 'block';
            }

            // Hide favorite button if the item belongs to the current user
            if (currentUser && currentUser.userId === item.sellerId) {
                favoriteBtn.style.display = 'none';
                const editItemBtn = document.getElementById('editItemBtn');
                editItemBtn.style.display = 'block'; // Show edit button
                editItemBtn.onclick = () => openEditModal(item); 

                // Check for unread comments for this item if current user is the seller
                checkUnreadCommentsForItem(itemId, currentUser.userId);

            } else {
                favoriteBtn.style.display = 'block';
                favoriteBtn.onclick = () => addFavorite(itemId);
                document.getElementById('editItemBtn').style.display = 'none'; 
            }

            // Load comments after item details are loaded
            loadComments(itemId);

        } catch (error) {
            console.error('加载商品详情失败:', error);
            favoriteBtn.style.display = 'none';
        }
    }

    async function addFavorite(itemId) {
        const currentUser = getCurrentUser(); // Get current user
        if (!currentUser || !currentUser.userId) {
            alert('请先登录才能收藏！');
            window.location.href = 'login.html'; // Redirect to login if not logged in
            return;
        }
        const userId = currentUser.userId;

        try {
            const token = localStorage.getItem('token');
            const headers = {
                'Content-Type': 'application/json',
                'Authorization': token ? 'Bearer ' + token : ''
            };
            const response = await fetch('/api/favorites', {
                method: 'POST',
                headers: headers,
                body: JSON.stringify({ userId: currentUser.userId, itemId: itemId })
            });

            if (response.ok) {
                 alert('已成功收藏该商品！');
            } else {
                // Handle potential errors, e.g., already favorited
                 const errorText = await response.text();
                 alert(`收藏失败: ${errorText}`);
                 console.error('收藏失败:', errorText);
            }

        } catch (error) {
            console.error('收藏失败:', error);
            alert('收藏失败，发生网络错误。');
        }
    }

    // Functions to control the edit modal
    function openEditModal(item) {
        document.getElementById('editItemModal').style.display = 'flex';
        // Populate the form with item data
        document.getElementById('editItemId').value = item.itemId;
        document.getElementById('editTitle').value = item.title;
        document.getElementById('editPrice').value = item.price;
        document.getElementById('editDescription').value = item.description;
        // Set selected status, default to '出售中' if item.status is null or undefined
        document.getElementById('editStatus').value = item.status || '出售中';
    }

    function closeEditModal() {
        document.getElementById('editItemModal').style.display = 'none';
    }

    // Handle form submission
    document.getElementById('editItemForm').addEventListener('submit', async function(event) {
        event.preventDefault(); // Prevent default form submission
        
        const itemId = document.getElementById('editItemId').value;
        // Use FormData to handle both text fields and file uploads
        const formData = new FormData();
        const itemDetails = {
            title: document.getElementById('editTitle').value,
            price: parseFloat(document.getElementById('editPrice').value),
            description: document.getElementById('editDescription').value,
            status: document.getElementById('editStatus').value
        };
        // Append item details as a JSON string part named 'itemDetails'
        formData.append('itemDetails', JSON.stringify(itemDetails));

        const imageFiles = document.getElementById('editImages').files;
        for (let i = 0; i < imageFiles.length; i++) {
            formData.append('images', imageFiles[i]);
        }

        console.log('Updated item data (FormData):', formData);

        // TODO: Send updatedItem to backend API to save
        try {
            const response = await fetch(`/api/items/${itemId}`, {
                method: 'PUT',
                // No 'Content-Type' header needed for FormData, browser sets it automatically
                body: formData
            });

            if (response.ok) {
                alert('商品信息更新成功！');
                closeEditModal();
                loadItemDetail(); // Reload item detail to show changes
            } else {
                const errorText = await response.text();
                alert(`更新失败: ${errorText}`);
                console.error('更新失败:', errorText);
            }
        } catch (error) {
            console.error('更新失败:', error);
            alert('更新失败，发生网络错误。');
        }
    });

    async function loadComments(itemId) {
        try {
                        const token = localStorage.getItem('token');
            const headers = {};
            if (token) {
                headers['Authorization'] = 'Bearer ' + token;
            }
            const response = await fetch(`/api/messages/item/${itemId}/comments`, { headers });
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const comments = await response.json();
            renderComments(comments);
        } catch (error) {
            console.error('加载评论失败:', error);
            document.getElementById('commentsList').innerHTML = '<p>加载评论失败。</p>';
        }
    }

    function renderComments(comments) {
        const commentsListDiv = document.getElementById('commentsList');
        commentsListDiv.innerHTML = ''; // Clear existing comments

        if (comments.length === 0) {
            commentsListDiv.innerHTML = '<p>暂无评论，快来发表第一条评论吧！</p>';
            return;
        }

        const currentUser = getCurrentUser(); // Get current user for permission check
        const itemSellerId = currentItemData ? currentItemData.sellerId : null; // Get item seller ID

        comments.forEach(comment => {
            const commentDiv = document.createElement('div');
            commentDiv.className = 'comment-item';
            
            // Determine if delete button should be shown
            const canDelete = currentUser && (
                currentUser.userId === comment.senderId || // Is the comment sender
                currentUser.userId === itemSellerId // Is the item seller
            );

            commentDiv.innerHTML = `
                <div class="comment-meta">
                    <span class="comment-author">${comment.senderNickname || '未知用户'}</span>
                    <span class="comment-date">${new Date(comment.createdAt).toLocaleString()}</span>
                    ${canDelete ? `<button class="delete-comment-btn" data-message-id="${comment.messageId}">删除</button>` : ''}
                </div>
                <p class="comment-content">${comment.content}</p>
            `;
            commentsListDiv.appendChild(commentDiv);

            // Add event listener for delete button if it exists
            if (canDelete) {
                const deleteButton = commentDiv.querySelector(`.delete-comment-btn[data-message-id="${comment.messageId}"]`);
                if (deleteButton) {
                    deleteButton.addEventListener('click', function() {
                        if (confirm('确定要删除这条评论吗？')) {
                            deleteComment(comment.messageId, currentUser.userId);
                        }
                    });
                }
            }
        });
    }

    // New function to handle comment deletion
    async function deleteComment(messageId, userId) {
        try {
            const response = await fetch(`/api/messages/comment/${messageId}/${userId}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('token') // Assuming token is needed
                }
            });

            if (response.ok) {
                alert('评论删除成功！');
                loadComments(currentItemData.itemId); // Reload comments after deletion
            } else {
                const errorText = await response.text();
                alert(`评论删除失败: ${errorText}`);
                console.error('评论删除失败:', errorText);
            }
        } catch (error) {
            console.error('删除评论失败:', error);
            alert('删除评论失败，发生网络错误。');
        }
    }

    document.getElementById('submitCommentBtn').addEventListener('click', async function() {
        const commentContent = document.getElementById('commentContent').value.trim();
        const currentUser = getCurrentUser();

        if (!currentUser || !currentUser.userId) {
            alert('请先登录才能发表评论！');
            window.location.href = 'login.html';
            return;
        }

        if (!commentContent) {
            alert('评论内容不能为空！');
            return;
        }

        if (!currentItemData || !currentItemData.itemId || !currentItemData.sellerId) {
            alert('无法获取商品信息，请刷新页面重试。');
            return;
        }
        console.log("Current item data before comment submission:", currentItemData); // Added log

        const commentData = {
            senderId: currentUser.userId,
            receiverId: currentItemData.sellerId, // The seller of the item is the receiver of the comment
            itemId: currentItemData.itemId,
            content: commentContent
        };

        console.log("Attempting to submit comment with data:", commentData); // Added log

        try {
            const token = localStorage.getItem('token');
            const headers = {
                'Content-Type': 'application/json'
            };
            if (token) {
                headers['Authorization'] = 'Bearer ' + token;
            }
            const response = await fetch('/api/messages/comment', {
                method: 'POST',
                headers: headers,
                body: JSON.stringify(commentData)
            });

            if (response.ok) {
                alert('评论发表成功！');
                document.getElementById('commentContent').value = ''; // Clear the input
                loadComments(currentItemData.itemId); // Reload comments
            } else {
                const errorText = await response.text();
                alert(`评论发表失败: ${errorText}`);
                console.error('评论发表失败:', errorText);
            }
        } catch (error) {
            console.error('评论发表失败:', error);
            alert('评论发表失败，发生网络错误。');
        }
    });

    // Function to check for unread comments on a specific item (for seller)
    async function checkUnreadCommentsForItem(itemId, sellerId) {
        const itemUnreadCommentsBadge = document.getElementById('itemUnreadCommentsBadge');
        if (!itemUnreadCommentsBadge) return; // Ensure element exists

        try {
                        const token = localStorage.getItem('token');
            const headers = {};
            if (token) {
                headers['Authorization'] = 'Bearer ' + token;
            }
            const response = await fetch(`/api/messages/unread-comments/item/${itemId}/${sellerId}`, { headers });
            if (!response.ok) {
                console.error("Failed to fetch unread comments status for item:", response.status, response.statusText);
                itemUnreadCommentsBadge.style.display = 'none';
                return;
            }
            const hasUnread = await response.json();
            if (hasUnread) {
                itemUnreadCommentsBadge.style.display = 'inline-block';
            } else {
                itemUnreadCommentsBadge.style.display = 'none';
            }
        } catch (error) {
            console.error("Error checking unread comments for item:", error);
            itemUnreadCommentsBadge.style.display = 'none';
        }
    }

    window.addEventListener('load', loadItemDetail);
</script>
</body>
</html>